import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xin_he/page/home/model/xin_he_goods_item_entity.dart';
import 'package:xin_he/page/home/model/xin_he_special_distract_entity.dart';
import 'package:xin_he/page/shopping_car/models/xin_he_goods_model.dart';
import 'package:xin_he/page/shopping_car/xin_he_shopping_car/xin_he_shopping_car_logic.dart';
import 'package:xin_he/service/xin_he_reqest.dart';

import '../../../utils/xin_he_event_bus.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_string_extension.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_home_state.dart';

class XinHeHomeLogic extends GetxController with GetTickerProviderStateMixin{
  final XinHeHomeState state = XinHeHomeState();

  List categoryTitleList = ['新鲜水果','生鲜菜品','粮油干货','生活用品','全部分类'];
  List categoryIconList = ['category_fruit','category_vegetables','category_rice','category_shower','category_all',];
  RxList bannerList = [].obs;

  late TabController tabController;
  // List tabs = ['帮扶专区','家园优品','链动专区','易品汇',];

  ///
  late TabController categoryTabController;
  List categoryTabs =['全部','新鲜水果','生鲜菜品','粮油干货','生活用品',];

  ///限时抢购
  Timer? _snapUpTimer;
  int secondsRemaining = 3610; // 倒计时的总秒数
  RxString snapUpHour = '00'.obs;
  RxString snapUpMinute = '00'.obs;
  RxString snapUpSecond = '00'.obs;



  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();




    startCountdown();

    bus.on(XinHeStorage.KNeedRefresh, (arg) async {

      if(arg == 0) {

      await  requestSpecialDistritTabData();

      await  requestAllTabData();
      }

    });

  }

  @override
  Future<void> onReady() async {
    // TODO: implement onReady
    super.onReady();

    await requestSpecialDistritTabData();

    await requestAllTabData();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    if(_snapUpTimer != null){
      _snapUpTimer?.cancel();
      _snapUpTimer = null;
    }
  }

  void startCountdown() {
    _snapUpTimer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      if (secondsRemaining > 0) {
        secondsRemaining--;
        int hours = secondsRemaining ~/ 3600;
        int minutes = (secondsRemaining % 3600) ~/ 60;
        int remainingSeconds = secondsRemaining % 60;

        String hoursStr = (hours < 10) ? '0$hours' : hours.toString();
        String minutesStr = (minutes < 10) ? '0$minutes' : minutes.toString();
        String secondsStr = (remainingSeconds < 10) ? '0$remainingSeconds' : remainingSeconds.toString();

        snapUpHour.value = hoursStr;
        snapUpMinute.value = minutesStr;
        snapUpSecond.value = secondsStr;
      } else {
        timer.cancel();
        snapUpHour.value = '00';
        snapUpMinute.value = '00';
        snapUpSecond.value = '00';
      }
    });
  }
  String formatTime(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int remainingSeconds = seconds % 60;

    String hoursStr = (hours < 10) ? '0$hours' : hours.toString();
    String minutesStr = (minutes < 10) ? '0$minutes' : minutes.toString();
    String secondsStr = (remainingSeconds < 10) ? '0$remainingSeconds' : remainingSeconds.toString();

    return '$hoursStr:$minutesStr:$secondsStr';
  }



  ///计算tab的边距
  double getPaddingWidth() {
    double leftW = Get.width - 65;
    var stringWidth = XinHeStringExtension.calculateTextHeight(
        getTotalTabsLength(categoryTabs), 16.0, FontWeight.w700, double.infinity, 1);

    double paddingW = (leftW - stringWidth) / (categoryTabs.length);
    if (paddingW < 0) return 0;
    if (categoryTabs.length == 5) {
      paddingW = (leftW - stringWidth) / (categoryTabs.length);
      return paddingW / 2;
    }
    paddingW = (leftW - stringWidth) / (categoryTabs.length);
    return paddingW / 2;
  }

  String getTotalTabsLength(List list) {
    String ss = '';
    for (String e in list) {
      ss = ss + e;
    }

    return ss;
  }


  ///添加商品进购物车
  void addGoodsToCartAction(XinHeGoodsModel model){
     XinHeToast.center('已添加');
     final allLogic = Get.find<XinHeShoppingCarLogic>();
     allLogic.state.allItemsList.add(model);

  }


  ///专区tab
  requestSpecialDistritTabData() async{
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goodsZoneType/queryGoodsZoneTypeList',isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }
    List list = result.data['data'] ??[];
    List <XinHeSpecialDistractEntity>items = [];

    if(list.isNotEmpty){
     for(var e in list){
       XinHeSpecialDistractEntity model = XinHeSpecialDistractEntity.fromJson(e);
       items.add(model);
     }

     tabController =
         TabController(vsync: this, length: items.length, initialIndex: 0);

     XinHeSpecialDistractEntity model = items[0];

     await requestSpecialDistritData(model.id);

     state.specialDistrictTabsList.value = items;

   }



  }

  ///专区data
  requestSpecialDistritData(tabId)async{
    Map<String,dynamic> ss = {
      'goodsZoneTypeId':'${tabId}'
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goodsZoneType/queryGoodsZoneTypeGoods',params: ss,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }


    List list = result.data['data'] ??[];
    List <XinHeGoodsItemEntity>items = [];

    if(list.isNotEmpty){
      for(var e in list){
        XinHeGoodsItemEntity model = XinHeGoodsItemEntity.fromJson(e);
        // model.iconPath = 'https://xhyp.quexiaoer.cn/upload/goods-photo/goods-photo_20230703074806830_3210.png';

        items.add(model);
      }
      state.specialDistrictTabsDetailList.value = items;
    }else {
      state.specialDistrictTabsDetailList.clear();

    }
  }

  ///all tab
  requestAllTabData()async{
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goodsType/queryGoodsTypeList',isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }
    List list = result.data['data'] ??[];
    List<XinHeSpecialDistractEntity> items = [];

    if(list.isNotEmpty){
      for(var e in list){
        XinHeSpecialDistractEntity model = XinHeSpecialDistractEntity.fromJson(e);
        items.add(model);
      }

      categoryTabController =
          TabController(vsync: this, length: items.length, initialIndex: 0);
      XinHeSpecialDistractEntity model = items[0];

      await   requestAllTabsDataItem(model.id);

      state.allTabList.value = items;

    }



  }

  ///all tab data
  requestAllTabsDataItem(tabId)async{

    Map<String,dynamic> ss = {
      'goodsTypeId':'${tabId}'
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goodsType/queryGoodsTypeGoods',params: ss,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }


    List list = result.data['data'] ??[];
    List <XinHeGoodsItemEntity>items = [];

    if(list.isNotEmpty){
      for(var e in list){
        XinHeGoodsItemEntity model = XinHeGoodsItemEntity.fromJson(e);
        // model.iconPath = 'https://xhyp.quexiaoer.cn/upload/goods-photo/goods-photo_20230703074806830_3210.png';

        items.add(model);
      }
      state.allTabDataList.value = items;
    }else {
      state.allTabDataList.clear();

    }
  }

}
